import SitePoolSelector from '@/components/SitePoolSelector';
import request from '@/request';
import { IPoolBasicRangeSearchParams } from '@/request/sheet/typing';
import { formatDate, formatPoolNos } from '@/utils/format';
import { flatRecordRes } from '@/utils/record';
import exportTableToExcel from '@/utils/sheet/exportXlsx';
import { Button, Form, Input, Modal, Popconfirm, Space, Table,DatePicker,message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';

const { RangePicker } = DatePicker;

interface ISheetData {
  // 防疫日期
  date: string;
  // 上报日期
  reportDate: string;
  // 上报人
  reporter: string;
  // 塘号
  poolNo: string;
  //防疫工作描述
  description: string;
}


const ImmunizationRecord = () => {
  const [showLoading, setShowLoading] = useState(false);
  const [sheetData, setSheetData]: [ISheetData[], any] = useState([]);
  const [modalOpen, setModalOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [dateRange, setDateRange]: [string[], any] = useState([
    // 默认当天前十五天数据
    dayjs().subtract(14, 'day').format('YYYY-MM-DD'),
    dayjs().format('YYYY-MM-DD'),
  ]);
  useEffect(() => {
    setShowLoading(true);
    request.record
      .getImmunizationRecordData({ date: dateRange })
      .then((res) => {
        const sheetData: ISheetData[] = [];
        for (let i = 0; i < res.data.length; i++) {
          const item = flatRecordRes(res.data[i]);
          item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
          sheetData.push(item);
        }
        sheetData.sort((a, b) => {
          return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
        });
        setSheetData(sheetData);
      })
      .finally(() => setShowLoading(false));
  }, []);

  const SearchBar: React.FC = () => {
    const onFinish = (values: IPoolBasicRangeSearchParams) => {
      setShowLoading(true);
      const dateArr = values.dateRange.map((value) => {
        return value.format('YYYY-MM-DD');
      });
      let poolNos: string[] = [];
      if (values.sitePool) poolNos = formatPoolNos(values.sitePool);
      request.record
        .getImmunizationRecordData({ poolNos, date: dateArr })
        .then((res) => {
          const sheetData: ISheetData[] = [];
          for (let i = 0; i < res.data.length; i++) {
            const item = flatRecordRes(res.data[i]);
            item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
            sheetData.push(item);
          }
          sheetData.sort((a, b) => {
            return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
          });
          setSheetData(sheetData);
          setDateRange(dateArr);
        })
        .finally(() => setShowLoading(false));
    };
    // 此处为新增防疫记录
    const [form] = Form.useForm();
    function handleCreate() {
      setConfirmLoading(true);
    
      form.validateFields().then((res: {  
        poolNo: string;
        userId:string;
        description: string;
        date:string;
        }) => {  
        request.record.addImmunizationRecordData({ ...res}).then((res) => {
          if (res.status === 200) {
           message.success('新增成功',2);
           // 添加成功后，重新获取数据
        setShowLoading(true);
        request.record
          .getImmunizationRecordData({ date: dateRange })
          .then((res) => {
            const sheetData: ISheetData[] = [];
            for (let i = 0; i < res.data.length; i++) {
              const item = flatRecordRes(res.data[i]);
              item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
              sheetData.push(item);
            }
            sheetData.sort((a, b) => {
              return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
            });
            setSheetData(sheetData);
          })
          .finally(() => setShowLoading(false));
          } else if (res.status === 201) {
            message.error(res.statusText, 2);
          }else{
            message.error('新增失败！', 2);
          }
        });
      });
      setConfirmLoading(false);
      setModalOpen(false);
    }
    //以上为新增防疫记录

    return (
      <div>
      <Form name="customized_form_controls" layout="inline" onFinish={onFinish} className="content-box search-bar">
        <SitePoolSelector type="pool" />
        <Form.Item name="dateRange" label="日期" rules={[{ required: true, message: '该项必填' }]}>
          <RangePicker
            disabledDate={(date) => {
              return date && date > dayjs().endOf('day');
            }}
            placeholder={['开始时间', '结束时间']}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
        </Form.Item>
        <Form.Item>
        <Button
          type="primary"
          style={{ backgroundColor: '#18bc69' }}
          onClick={() => exportTableToExcel('medication-record-table', 'medication-record-table')}
        >
          导出
        </Button>
        </Form.Item>
        <Form.Item>
        <Button type="primary" onClick={() => setModalOpen(true)}>
          新增
        </Button>
        </Form.Item>
      </Form>
       <Modal
       title="新增防疫记录"
       open={modalOpen}
       onOk={handleCreate}
       confirmLoading={confirmLoading}
       cancelText="取消"
       okText="确认新增"
       onCancel={() => setModalOpen(false)}
     >
       <Form name="addRecord" style={{ padding: '20px' }} form={form}>
         <Form.Item label="塘号" name="poolNo" rules={[{ required: true, message: '塘号为空' }]}>
           <Input placeholder="请输入塘号" allowClear={true} />
         </Form.Item>
         <Form.Item label="上报人" name="userId" rules={[{ required: true, message: '上报人为空' }]}>
           <Input placeholder="请输入用户名" allowClear={true} />
         </Form.Item>
         <Form.Item label="防疫工作描述" name="description" rules={[{ required: true, message: '防疫工作描述为空' }]}>
           <Input placeholder="请输入防疫工作描述" allowClear={true} />
         </Form.Item>
         <Form.Item
           label="防疫工作日期"
           name="date"
           rules={[{ required: true, message: '用药日期为空' }]}
         >
            <DatePicker format="YYYY-MM-DD" value-Format="YYYY-MM-DD" />
         </Form.Item>
       </Form>
     </Modal>
   </div>
    );
  };

  const TableContainer = () => {
    const columns: ColumnsType<ISheetData> = [
      {
        title: '塘号',
        dataIndex: 'poolNo',
        key: 'poolNo',
        align: 'center',
        fixed: 'left',
        className: 'first-column',
      },
      {
        title: '上报人',
        dataIndex: 'reporter',
        key: 'reporter',
        align: 'center',
      },
      {
        title: '防疫工作日期',
        dataIndex: 'date',
        key: 'date',
        align: 'center',
        render: (value) => formatDate(value),
      },
      {
        title: '防疫工作描述',
        dataIndex: 'description',
        key: 'description',
        align: 'center',
      },
      {
        title: '上报日期',
        dataIndex: 'reportDate',
        key: 'reportDate',
        align: 'center',
        render: (value) => formatDate(value),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        align: 'center',
        render: (_, record: ISheetData) => (
          <Space className="operation">
             <a className="operation-item edit" onClick={() => handleEdit(record)}>
              修改
            </a>
            <Popconfirm title="确认删除该条数据？" onConfirm={() => handleDelete(record)}>
              <a style={{ color: 'red' }}>删除</a>
            </Popconfirm>
          </Space>
        ),
      },
     
    ];
    function handleDelete(record: ISheetData) {
      // 从record对象中获取poolNo和date
      const { poolNo, date } = record;

      // 发送请求以删除数据
      request.record
      .deleteImmunizationRecordData({poolNo, date}).then((res) => {
        if (res.status === 200) {
          // 删除成功后，更新本地状态
        setSheetData((prevData) =>
          prevData.filter((item) => item.poolNo !== poolNo || item.date !== date)
        );
        }
        setShowLoading(false);
      });
      message.success({
        duration: 2,
        content: '删除成功',
      });
    }
      // 此处为修改防疫记录
      const layout = {
        labelCol: { span: 8 },
        wrapperCol: { span: 16 },
      };   
      function convertDateFormat(dateString) {
        // 假设输入格式为 MM/DD/YYYY
        const parts = dateString.split('/');
        // 转换为 YYYY-MM-DD 格式
        return `${parts[0]}-${parts[1]}-${parts[2]}`;
      }   
    const [form] = Form.useForm();
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editingRecord, setEditingRecord]: [ISheetData[], any] = useState([]);
    const handleEdit = (record: ISheetData) => {
      setEditModalOpen(true);
      setEditingRecord(record);
    };
    const EditModal = (props: { record: ISheetData}) => {
    const { record } = props;
    function handleEditSubmit() {
        setConfirmLoading(true);
        form.validateFields().then((res) => {
          request.record
          .editImmunizationRecordData({poolNo: res.poolNo, description: res.description,date:res.date })
          .then((res) => {
            if (res.status === 200) {
              message.success('修改成功', 2);
                 // 添加成功后，重新获取数据
             
              request.record
                .getImmunizationRecordData({ date: dateRange })
                .then((res) => {
                  const sheetData: ISheetData[] = [];
                  for (let i = 0; i < res.data.length; i++) {
                    const item = flatRecordRes(res.data[i]);
                    item['key'] = res.data[i].reportBasic.poolNo + '/' + res.data[i].reportBasic.date + i;
                    sheetData.push(item);
                  }
                  sheetData.sort((a, b) => {
                    return dayjs(b.date).valueOf() - dayjs(a.date).valueOf(); // 降序排序
                  });
                  setSheetData(sheetData);
                  
                })
            } else message.error('修改失败', 2);
          })
          .finally(() => {
            setConfirmLoading(false);
            setEditModalOpen(false);
          
          });
        });
      }
    return (
      <Modal
          title="修改防疫记录"
          open={editModalOpen}
          onOk={handleEditSubmit} // 处理编辑提交的方法
          confirmLoading={confirmLoading}
          cancelText="取消"
          okText="确认修改"
          onCancel={() => {
            setEditModalOpen(false);
          }}
        >
        <Form
              style={{ padding: '20px' }}
              {...layout}
              wrapperCol={{ span: 18 }}
              form={form}
              name="editImmunication"
              autoComplete="off"
              initialValues={{ items: [{}] }}
            >          
          <Form.Item initialValue={record.poolNo} label="塘号" name="poolNo" >
            <Input disabled />
          </Form.Item>
          <Form.Item initialValue={record.reporter} label="上报人" name="userId">
                <Input disabled />
          </Form.Item>
          <Form.Item
           label="防疫日期"
           name="date"
           initialValue={convertDateFormat(new Date(record.date).toLocaleString('zh-TW', { year: 'numeric', month: '2-digit', day: '2-digit' }))}
         >
              <Input disabled />
         </Form.Item>
          <Form.Item label="防疫工作描述" initialValue={record.description} name="description" rules={[{ required: true, message: '防疫工作描述为空' }]}>
            <Input placeholder="请输入防疫工作描述" allowClear={true} value={record?.description} />
          </Form.Item>
        </Form>
      </Modal>
    );
    };
     // 此上为修改防疫记录
    return (
      <div className="content-box">
        <Table
          dataSource={sheetData}
          bordered
          pagination={{ pageSize: 1000 }}
          size="small"
          columns={columns}
          id="feed-record-table"
          rowKey={'key'}
          title={() => {
            return `总共匹配到：${sheetData.length}条数据，数据自${dateRange[0]}算起，到${dateRange[1]}。`;
          }}
          loading={showLoading}
        />
         <EditModal record={editingRecord} />
      </div>
    );
  };

  return (
    <div>
      <SearchBar />
      <TableContainer />
    </div>
  );
};
export default ImmunizationRecord;
